package com.metamech.vorpal.handler;

import java.io.Writer;

import org.apache.log4j.Logger;

import com.metamech.jabber.Authenticator;
import com.metamech.jabber.Session;
import com.metamech.jabber.xml.Packet;
import com.metamech.jabber.xml.PacketListener;
import com.metamech.log.Log;
import com.metamech.vorpal.Server;
import com.metamech.vorpal.UserIndex;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author
 * @version 1.0
 */

public class OpenStreamHandler implements PacketListener{
	private static Logger logger=Logger.getLogger(OpenStreamHandler.class);
	static int streamID = 0;
	//SessionIndex sessionIndex;

	/*public OpenStreamHandler(SessionIndex index) {
		sessionIndex = index;
	}*/
	UserIndex userIndex;

	public OpenStreamHandler(UserIndex index) {
		userIndex = index;
	}

	/*public void notify(Packet packet){
		Log.trace("Opening stream connection");

		try {
			Session session = packet.getSession();
			session.setJID(new JabberID(packet.getFrom()));
			sessionIndex.addSession(session);

			session.setStreamID(Integer.toHexString(streamID++));

			Writer out = session.getWriter();
			out.write("<?xml version='1.0' encoding='UTF-8' ?><stream:stream xmlns='jabber:client' from='");
			out.write(Server.SERVER_NAME);
			out.write("' id='");
			out.write(session.getStreamID());
			out.write("' xmlns:stream='http://etherx.jabber.org/streams'>");
			out.flush();

			session.setStatus(Session.STREAMING);
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}*/
	public void notify(Packet packet){
		logger.info("Opening stream connection");

	    try {
	      Session session = packet.getSession();

	      session.setStreamID(Authenticator.randomToken());

	      Writer out = session.getWriter();
	      out.write("<?xml version='1.0' encoding='UTF-8' ?><stream:stream xmlns='jabber:client' from='");
	      out.write(Server.SERVER_NAME);
	      out.write("' id='");
	      out.write(session.getStreamID());
	      out.write("' xmlns:stream='http://etherx.jabber.org/streams'>");
	      out.flush();

	      session.setStatus(Session.STREAMING);
	    } catch (Exception ex){
	      ex.printStackTrace();
	    }
	}
}